// 应用路由器组件
import React, { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { useRouterStore } from '../../stores/routerStore';
import { ViewType } from '../../types/router';
import { EditorView, DashboardView, GraphView, SettingsView } from '../../views';

// 路由同步组件 - 同步React Router和我们的路由状态
const RouteSync: React.FC = () => {
  const location = useLocation();
  const navigate = useRouterStore(state => state.navigate);

  useEffect(() => {
    // 当React Router路径变化时，同步到我们的路由状态
    const pathToViewType: Record<string, ViewType> = {
      '/editor': ViewType.EDITOR,
      '/dashboard': ViewType.DASHBOARD,
      '/graph': ViewType.GRAPH,
      '/settings': ViewType.SETTINGS,
    };

    const viewType = pathToViewType[location.pathname];
    if (viewType) {
      navigate(location.pathname, viewType);
    }
  }, [location.pathname, navigate]);

  return null;
};

// 路由内容组件
const RouterContent: React.FC = () => {
  return (
    <>
      <RouteSync />
      <Routes>
        <Route path="/editor" element={<EditorView />} />
        <Route path="/dashboard" element={<DashboardView />} />
        <Route path="/graph" element={<GraphView />} />
        <Route path="/settings" element={<SettingsView />} />
        <Route path="/" element={<Navigate to="/editor" replace />} />
        <Route path="*" element={<Navigate to="/editor" replace />} />
      </Routes>
    </>
  );
};

interface AppRouterProps {
  className?: string;
}

export const AppRouter: React.FC<AppRouterProps> = ({ className }) => {
  return (
    <div className={`flex-1 flex flex-col ${className || ''}`}>
      <BrowserRouter>
        <RouterContent />
      </BrowserRouter>
    </div>
  );
};
